package br.com.vti.leilao.model.business;

import br.com.vti.leilao.model.entity.Usuario;
import br.com.vti.leilao.model.business.exception.ApplicationException;
import br.com.vti.leilao.model.dao.Dao;
import br.com.vti.leilao.view.util.MessageFactory;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author ednardomatos
 */
@Component
@Transactional(readOnly = true)
public class UsuarioBusiness extends BusinessImpl<Usuario, ApplicationException> implements UserDetailsService {
    
    private static final long serialVersionUID = -3897867461694722465L;
    
    @Autowired
    @Qualifier("dao")
    private Dao<Usuario> dao;
        
    @Autowired
    @Qualifier("messageFactory")
    private MessageFactory messageFactory;

    @Override
    public Dao<Usuario> getDao() {
        return dao;
    }

    @Override
    public void setDao(Dao<Usuario> dao) {
        this.dao = dao;
    }

    @Override
    public MessageFactory getMessageFactory() {
        return messageFactory;
    }

    @Override
    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }
    
    @Override
    public Usuario loadUserByUsername(String email) throws UsernameNotFoundException {
        Usuario usuario = null;
        if (email != null && !email.isEmpty()) {
            String hql = "FROM Usuario WHERE UPPER(email) = UPPER(:email)";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("email", email);
            try {
                List<Usuario> lista = getDao().listarPorHql(hql, parametros, 10);
                if (lista.isEmpty() || lista.size() > 1) {
                    throw new UsernameNotFoundException("");
                } else if (lista.get(0).getStatus() != 'A') {
                    throw new DisabledException("");
                } else {
                    usuario = lista.get(0);
                }
            } catch (SQLException e) {
                lancarException(e, BUSCAR);
            }
        }
        return usuario;
    }
    
}
